<template>
  <div class="main-wrapper">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.statusName" :value="item.key" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreateNew">添加最新项目</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreateDeal">添加最近成交</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
      <el-table-column label="项目名称" align="center">
        <template slot-scope="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column label="专业信息" align="center">
        <template slot-scope="{row}">
          {{ row.profession }}
        </template>
      </el-table-column>
      <el-table-column label="图片链接地址" align="center">
        <template slot-scope="{row}">
          <el-image :src="getFullImageUrl(row.imgUrl)" />
        </template>
      </el-table-column>
      <el-table-column label="价格信息" align="center">
        <template slot-scope="{row}">
          {{ row.price }}
        </template>
      </el-table-column>
      <el-table-column label="地址信息" align="center">
        <template slot-scope="{row}">
          {{ row.area }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | styleFilter()">{{ row.status | statusFilter() }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{row}">
          {{ row.type | typeFilter() }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">上传图片</el-button>
          <el-button v-if="row.status!=0" size="mini" type="danger" @click="delHomeProject(row)">删除</el-button>
          <el-button v-if="row.status!=1" size="mini" type="success" @click="reuseHomeProject(row)">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchHomeProjectList" />

    <el-dialog width="68%" top="3hv" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="homeProjectData" label-position="left" label-width="90px">
        <el-form-item label="类型">
          <span>{{ homeProjectData.typeName }}</span>
        </el-form-item>
        <el-form-item label="项目名称">
          <span>{{ homeProjectData.name }}</span>
        </el-form-item>
        <el-form-item label="专业信息">
          <span>{{ homeProjectData.professionName }}</span>
        </el-form-item>
        <el-form-item label="图片链接地址">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :http-request="uploadImage"
          >
            <img v-if="homeProjectData.imgUrl" :src="getFullImageUrl(homeProjectData.imgUrl)" class="avatar">
            <i v-else class="el-icon-upload avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="价格信息">
          <span>{{ homeProjectData.price }}</span>
        </el-form-item>
        <el-form-item label="地址信息">
          <span>{{ homeProjectData.area }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="homeProjectData.status | styleFilter()">{{ homeProjectData.statusName }}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createHomeProject():updateHomeProject()">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择项目" top="3vh" width="68%" :visible.sync="dialogProjectVisible">
      <el-table
        ref="multipleTable"
        :data="projectList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="项目名称" align="center">
          <template slot-scope="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column label="所在省市" align="center">
          <template slot-scope="{row}">
            {{ row.provinceName }}{{ row.cityName }}
          </template>
        </el-table-column>
        <el-table-column label="项目价格" align="center">
          <template slot-scope="{row}">
            {{ (row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="项目类型" align="center">
          <template slot-scope="{row}">
            {{ row.categoryName }}
          </template>
        </el-table-column>
        <el-table-column label="专业" align="center">
          <template slot-scope="{row}">
            {{ row.professionName }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="{row}">
            <span>{{ row.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="92">
          <template slot-scope="{row}">
            <el-tag :type="row.status | styleFilter()">{{ row.statusName }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogProjectVisible = false">取 消</el-button>
        <el-button type="primary" @click="createNewProject">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getHomeProjectList, addHomeProject, editHomeProject, editHomeProjectStatus } from '@/api/homeProject'
import { getByXml, getImageUrl, parseTime } from '@/utils'
import { uploadFileData } from '@/api/upload'
import { getProjectList } from '@/api/project'
import Pagination from '@/components/Pagination'

export default {
  name: 'HomeProject',
  components: {
    Pagination
  },
  filters: {
    styleFilter(style) {
      const styleMap = { 1: 'success', 0: 'danger' }
      return styleMap[style]
    },
    timeFilter(time, format) {
      return parseTime(time, format)
    },
    statusFilter(value) {
      const statusMap = { 0: '无效', 1: '有效' }
      return statusMap[value]
    },
    typeFilter(value) {
      const statusMap = { 1: '最新工程', 2: '最近成交' }
      return statusMap[value]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      statusOptions: [
        { key: 0, statusName: '无效' },
        { key: 1, statusName: '有效' }
      ],
      homeTypeMap: { 1: '最新项目', 2: '最近成交' },
      homeProjectData: {},
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogProjectVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {},
      projectList: [],
      selectedProjects: [],
      homeType: 0
    }
  },
  created() {
    this.fetchHomeProjectList()
  },
  methods: {
    fetchHomeProjectList() {
      this.listLoading = true
      getHomeProjectList(this.listQuery).then(response => {
        this.list = response.data
        // this.total = response.data.total
        console.log(this.list)
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchHomeProjectList()
    },
    resetHomeProjectData() {
      this.homeProjectData = {}
    },
    handleCreateNew() {
      this.homeType = 1
      this.resetHomeProjectData()
      this.selectedProjects = []
      this.fetchProjectList(10)
      this.dialogStatus = 'create'
      this.dialogProjectVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    handleCreateDeal() {
      this.homeType = 2
      this.resetHomeProjectData()
      this.selectedProjects = []
      this.fetchProjectList(40)
      this.dialogStatus = 'create'
      this.dialogProjectVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createNewProject() {
      this.list = this.selectedProjects.map(item => {
        console.log(item)
        const newProject = {
          projectId: item.id,
          name: item.name,
          profession: item.professionId,
          professionName: item.professionName,
          imgUrl: '',
          price: item.price,
          area: item.provinceName + item.cityName,
          type: this.homeType,
          typeName: this.homeTypeMap[this.homeType],
          createTime: new Date(),
          statusName: item.statusName
        }
        addHomeProject(newProject).then((response) => {
          this.fetchHomeProjectList()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
        return newProject
      })
      this.dialogProjectVisible = false
    },
    createHomeProject() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addHomeProject(this.homeProjectData).then((response) => {
            this.fetchHomeProjectList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.homeProjectData = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateHomeProject() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.homeProjectData)
          editHomeProject(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.homeProjectData.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.homeProjectData)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    delHomeProject(row) {
      row.status = 0
      this.updateHomeProjectStatus(row, 0)
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    reuseHomeProject(row) {
      row.status = 1
      this.updateHomeProjectStatus(row, 1)
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    updateHomeProjectStatus(row, status) {
      row.status = status
      editHomeProjectStatus(row.id, status).then(() => {
        this.homeProjectData = Object.assign({}, row)
        this.homeProjectData.status = status
        for (const v of this.list) {
          if (v.id === this.homeProjectData.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.homeProjectData)
            break
          }
        }
      })
      this.$message({
        message: '操作成功',
        type: 'success'
      })
    },
    fetchProjectList(status) {
      getProjectList({}).then(res => {
        this.projectList = res.data.items
      })
    },
    handleSelectionChange(val) {
      console.log('handleSelectionChange====', val)
      this.selectedProjects = val
    },
    uploadImage(e) {
      uploadFileData(e.file).then(res => {
        console.log(res)
        this.homeProjectData.imgUrl = getByXml(res, 'Key')
        console.log(this.homeProjectData)
      })
    },
    getFullImageUrl(imgName) {
      return getImageUrl(imgName)
    }
  }
}
</script>
<style lang="scss" scoped>
.main-wrapper {
  margin: 8px;
  .filter-container {
    padding: 10px 0;
    .filter-item {
      width: 200px;
      margin-right: 10px;
    }
  }
  .image-uploader {
    border: 1px dashed #d9d9d9;
    width: 278px;
    height: 178px;
    .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 278px;
      height: 178px;
      display: block;
    }
  }
}
</style>
